package cn.amos.core.business.impl;

import cn.amos.core.business.UserBusiness;
import cn.amos.dao.entity.UserEntity;
import cn.amos.dao.persistence.UserMapper;
import cn.amos.dao.search.UserSearch;
import cn.amos.facade.request.UserForm;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author DaoyuanWang
 */
@Component("userBusiness")
public class UserBusinessImpl implements UserBusiness {

    @SuppressWarnings("all")
    @Resource
    private UserMapper userMapper;

    @Override
    public String register(UserForm userForm) {
        UserSearch userSearch = new UserSearch();
        userSearch.setPhone(userForm.getPhone());
        UserEntity userEntityOld = userMapper.selectByExample(userSearch);
        if (userEntityOld != null) {
            return "该手机号已注册,请更换手机号注册";
        }

        UserEntity userEntity = new UserEntity();
        userEntity.setName(userForm.getName());
        userEntity.setPwd(userForm.getPwd());
        userEntity.setPhone(userForm.getPhone());
        userEntity.setStatus(true);
        userEntity.setUpdateTime(new Date());
        userEntity.setCreateTime(new Date());
        userMapper.insert(userEntity);

        return null;
    }

    @Override
    public UserEntity login(UserForm userForm) {
        UserSearch search = new UserSearch();
        search.setPhone(userForm.getPhone());
        search.setPwd(userForm.getPwd());
        return userMapper.selectByExample(search);
    }

    @Override
    public boolean existUser(String name) {
        UserSearch search = new UserSearch();
        search.setName(name);
        return userMapper.selectByExample(search) != null;
    }

    @Override
    public void update(UserForm userForm) {
        UserEntity userEntity = new UserEntity();
        userEntity.setUserId(userForm.getUserId());
        userEntity.setName(userForm.getName());
        userEntity.setPhone(userForm.getPhone());
        userEntity.setAge(userForm.getAge());
        userEntity.setGender(userForm.getGender());
        userEntity.setEmail(userForm.getEmail());
        userEntity.setUpdateTime(new Date());
        userMapper.update(userEntity);
    }

    @Override
    public String updatePwd(UserForm userForm) {
        UserSearch userSearch = new UserSearch();
        userSearch.setPhone(userForm.getPhone());
        userSearch.setName(userForm.getName());
        UserEntity userEntity = userMapper.selectByExample(userSearch);
        if (userEntity == null) {
            return "用户名输入错误或上一步输入的手机号错误";
        }
        userEntity.setUserId(userForm.getUserId());
        userEntity.setPwd(userForm.getPwd());
        userMapper.update(userEntity);

        return null;
    }
}
